#!/bin/sh

# enum
INDEX_MAJOR=1
INDEX_MINOR=2
INDEX_PATCH=3

# const
SUFFIX=
HEAD_COMMIT=$(git log HEAD --oneline -1 | awk '{print $1}')
TAG_RECENT=$(git describe --tags --abbrev=0 --match "v*")
if [ -z "$TAG_RECENT" ]; then
    echo "No-recent-semver-tag"
    exit 1
fi
TAG_COMMIT=$(git log $TAG_RECENT --oneline -1 | awk '{print $1}')

# 暂时用不上的函数
get_pos_ver_by_index() {
    ver=$(echo $TAG_RECENT | grep -Eo "(([0-9]+)\.*){3}" | awk -v i=$1 'BEGIN{FS="."}{print $i}')
    # 给予默认值0
    if [ -z $ver ]; then
        ver=0
    fi
    echo $ver
}

# 暂时用不上的函数
# 支持用'|'分隔type（某些情况下需要转义）
get_commit_cnt_by_types() {
    start=HEAD
    # 只看fix或者feat
    git log --pretty=format:'%s' $start...$TAG_RECENT | grep -cE "^(fix|feat)"
}

if [ "$HEAD_COMMIT" != "$(git log $TAG_RECENT --oneline -1 | awk '{print $1}')" ]; then
    # Recent tag not attached with HEAD, set version as 'latest'
    echo "latest"
    exit 0
fi
echo "$(echo $TAG_RECENT | tr -d "v")$SUFFIX"
